<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    h3{
      margin: 5vh 0;
      text-align: center;
    }
    .main{

      width: 100vw;
      height: 3vh;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
    .left,.right{
      margin: 0 10px;
    }
    .left{
      margin-bottom: 10px;
      width: 400px;
      min-height: 300px;
      border: 1px solid rgb(25, 137, 250);
    }
    .options{
      text-align: center;
      margin-bottom: 10px;
    }
    button{
      border: none;
      padding: 5px 20px; 
      color: #fff;
      background-color: rgb(25, 137, 250);
    }
    img{
      width: 100%;
    }
  </style>
</head>
<body>
  <h3>base64 图片 加/解密</h3>
  <div class="options">
    <input type="file" id="img" onchange="changepic(this)" accept="image/jpg,image/jpeg,image/png,image/PNG">
    <button id="code">生成base64</button>
    <button id="reduction">还原base64</button>
  </div>
  <div class="main">
    <div class="left">
      
    </div>
    <div class="right">
      <textarea id="text" cols="49" rows="20" placeholder="base64"></textarea>
    </div>
  </div>
  <script>
    let Oimg = ''
    function changepic(even){
      if(even.files && even.files[0]){
        Oimg = even.files[0]
        let url = window.URL.createObjectURL(even.files[0])
        document.getElementsByClassName('left')[0].innerHTML = `<img src="${url}"></img>`
      }
    }

    let codeBtn = document.getElementById('code')
    codeBtn.onclick =  function(){
      if(Oimg){
        let reader = new FileReader()
        reader.readAsDataURL(Oimg)
        reader.onload = function(even){
          base64 = even.target.result
          document.getElementById('text').value = base64
        }
      }else{
       alert('请先上传') 
      }
    }

    let Oreduction = document.getElementById('reduction')
    Oreduction.onclick = function(){
      let val =  document.getElementById('text').value
      if(val){
        document.getElementsByClassName('left')[0].innerHTML = `<img src="${val}"></img>`
      }else{
        alert('请先填写base64编码') 
      }
    }
  </script>
</body>
</html>